<template>
  <div class="page-wrapper">
    <!-- Page body -->
    <div class="page-body">
      <div class="container-xl">
        <div class="row row-deck row-cards">
          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <div class="row g-2 align-items-center">
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-primary w-100" @click="fetchData">
                      刷新列表
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-info w-100" @click="toggleSearchPanel">
                      {{ showSearchPanel ? '收起搜索' : '高级搜索' }}
                    </a>
                  </div>
                </div>
              </div>
              
              <!-- 高级搜索面板 -->
              <div class="card-body border-bottom" v-show="showSearchPanel">
                <div class="row g-3">
                  <div class="col-md-3">
                    <label class="form-label">操作类型</label>
                    <select class="form-select" v-model="searchParams.type">
                      <option value="">全部类型</option>
                      <option value="远程连接">远程连接</option>
                      <option value="远程连接失败">远程连接失败</option>
                      <option value="关闭远程连接">关闭远程连接</option>
                    </select>
                  </div>
                  <div class="col-md-3">
                    <label class="form-label">备注关键词</label>
                    <input type="text" 
                           class="form-control" 
                           v-model="searchParams.remark"
                           placeholder="搜索备注内容">
                  </div>
                  <div class="col-md-3">
                    <label class="form-label">开始时间</label>
                    <input type="datetime-local" 
                           class="form-control" 
                           v-model="searchParams.startTime">
                  </div>
                  <div class="col-md-3">
                    <label class="form-label">结束时间</label>
                    <input type="datetime-local" 
                           class="form-control" 
                           v-model="searchParams.endTime">
                  </div>
                </div>
                <div class="row mt-3">
                  <div class="col-12">
                    <button class="btn btn-primary me-2" @click="handleSearch">
                      搜索
                    </button>
                    <button class="btn btn-secondary" @click="resetSearch">
                      重置
                    </button>
                  </div>
                </div>
              </div>
              <div class="card-body border-bottom py-3">
                <div class="d-flex">
                  <div class="text-secondary">
                    共 {{ paginationInfo.total || 0 }} 条操作日志
                  </div>
                  <div class="ms-auto">
                    <!-- 分页信息 -->
                    <span class="text-secondary me-3">
                      第 {{ paginationInfo.current || 1 }} 页 / 共 {{ paginationInfo.pages || 1 }} 页
                    </span>
                    <div class="btn-group">
                      <button class="btn btn-sm btn-outline-primary" 
                              @click="goToPage(1)" 
                              :disabled="paginationInfo.current <= 1">
                        首页
                      </button>
                      <button class="btn btn-sm btn-outline-primary" 
                              @click="goToPage(paginationInfo.current - 1)" 
                              :disabled="paginationInfo.current <= 1">
                        上一页
                      </button>
                      <button class="btn btn-sm btn-outline-primary" 
                              @click="goToPage(paginationInfo.current + 1)" 
                              :disabled="paginationInfo.current >= paginationInfo.pages">
                        下一页
                      </button>
                      <button class="btn btn-sm btn-outline-primary" 
                              @click="goToPage(paginationInfo.pages)" 
                              :disabled="paginationInfo.current >= paginationInfo.pages">
                        末页
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <div class="table-responsive">
                <table class="table card-table table-vcenter text-nowrap datatable">
                  <thead>
                  <tr>
                    <th class="w-1">ID</th>
                    <th>操作类型</th>
                    <th>备注信息</th>
                    <th>创建时间</th>
                  </tr>
                  </thead>
                  <tbody>
                  <tr v-for="(item, index) in tableData" 
                      :key="item.id || index">
                    <td><span class="text-secondary">{{ item.id }}</span></td>
                    <td>
                      <span :class="{
                        'badge': true,
                        'bg-blue-lt': item.type === '远程连接',
                        'bg-red-lt': item.type === '远程连接失败',
                        'bg-green-lt': item.type === '定时任务-远程连接',
                        'bg-yellow-lt': item.type === '定时任务-关闭远程连接',
                        'bg-purple-lt': item.type === '定时任务-执行失败',
                        'bg-gray-lt': !['远程连接', '远程连接失败', '定时任务-远程连接', '定时任务-关闭远程连接', '定时任务-执行失败'].includes(item.type)
                      }">
                        {{ item.type }}
                      </span>
                    </td>
                    <td :title="item.remark" class="remark-cell">
                      {{ truncateText(item.remark, 80) }}
                    </td>
                    <td>{{ item.createTime }}</td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 使用封装的模态框组件 -->
  <ComponentModal
      :modalId="'modal-operate-log'"
      :title="'信息'"
      :message="'操作成功'"
      :cancelText="'取消'"
      :confirmText="'确定'"
      ref="componentModalOutRef"
  />

  <Loading ref="loadingRef"/>
</template>

<script setup>
import {ref, computed, onMounted, watch, nextTick} from 'vue';
import { useRoute } from 'vue-router';
import ComponentModal from '@/components/ComponentModal.vue';
import Loading from '@/components/Loading.vue';
import { useTableMixin } from '@/mixins/tableMixin';

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
// 表格数据和搜索
const tableData = ref([]);
const showSearchPanel = ref(false);

// 搜索参数
const searchParams = ref({
  type: '',
  remark: '',
  startTime: '',
  endTime: ''
});

// 分页参数
const pageParams = ref({
  offset: 0,
  limit: 20,
  sort: 'create_time',
  order: 'desc'
});

// 分页信息
const paginationInfo = ref({
  total: 0,
  current: 1,
  pages: 1,
  size: 20
});

const componentModalOutRef = ref(null);
const loadingRef = ref(null);

const route = useRoute();

// 查询数据的函数
const fetchData = async () => {
  if (!loadingRef.value) {
    console.warn('Loading component not initialized yet');
    return;
  }

  try {
    loadingRef.value.openLoading();
    
    // 构建请求参数
    const requestData = {
      search: {},
      offset: pageParams.value.offset,
      limit: pageParams.value.limit,
      sort: pageParams.value.sort,
      order: pageParams.value.order
    };

    // 添加搜索条件
    if (searchParams.value.type) {
      requestData.search.type = searchParams.value.type;
    }
    if (searchParams.value.remark) {
      requestData.search.remark = searchParams.value.remark;
    }
    if (searchParams.value.startTime) {
      requestData.search.startTime = formatDateTime(searchParams.value.startTime);
    }
    if (searchParams.value.endTime) {
      requestData.search.endTime = formatDateTime(searchParams.value.endTime);
    }

    const response = await fetch(apiBaseUrl + '/resident/operation-log/page', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    });
    
    const data = await response.json();
    
    if (data.success) {
      tableData.value = data.result.records || [];
      paginationInfo.value = {
        total: data.result.total || 0,
        current: data.result.current || 1,
        pages: data.result.pages || 1,
        size: data.result.size || 20
      };
    } else {
      componentModalOutRef.value?.openWarnModal(data.errorMsg || data.message || '加载操作日志数据失败');
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    componentModalOutRef.value?.openWarnModal('加载操作日志数据失败，请稍后重试！');
  } finally {
    loadingRef.value?.closeLoading();
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeLocal) => {
  if (!dateTimeLocal) return '';
  // 将 datetime-local 格式转换为 yyyy-MM-dd HH:mm:ss 格式
  return dateTimeLocal.replace('T', ' ') + ':00';
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  console.log('当前路由路径:', newPath);
  if (newPath === '/resident-web/operate-log' || newPath === '/operate-log') {
    console.log('进入操作日志页面，开始加载数据');
    // 延迟执行 fetchData，确保组件已挂载
    nextTick(() => {
      fetchData();
    });
  }
}, { immediate: true });

// 切换搜索面板
const toggleSearchPanel = () => {
  showSearchPanel.value = !showSearchPanel.value;
};

// 处理搜索
const handleSearch = () => {
  // 重置分页到第一页
  pageParams.value.offset = 0;
  paginationInfo.value.current = 1;
  fetchData();
};

// 重置搜索条件
const resetSearch = () => {
  searchParams.value = {
    type: '',
    remark: '',
    startTime: '',
    endTime: ''
  };
  handleSearch();
};

// 分页跳转
const goToPage = (page) => {
  if (page < 1 || page > paginationInfo.value.pages) return;
  
  pageParams.value.offset = (page - 1) * pageParams.value.limit;
  paginationInfo.value.current = page;
  fetchData();
};

// 添加文本截断函数
const truncateText = (text, length) => {
  if (!text) return '';
  return text.length > length ? text.substring(0, length) + '...' : text;
};

onMounted(() => {
  console.log('组件已挂载，当前路径:', route.path);
  // 如果当前路径是操作日志页面，则加载数据
  if (route.path === '/resident-web/operate-log' || route.path === '/operate-log') {
    fetchData();
  }
});
</script>

<style scoped>
/* 状态样式 */
.bg-green-lt {
  background-color: rgba(40, 167, 69, 0.15) !important;
  color: #2fb344 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-red-lt {
  background-color: rgba(220, 53, 69, 0.15) !important;
  color: #d63939 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-blue-lt {
  background-color: rgba(32, 107, 196, 0.15) !important;
  color: #206bc4 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-yellow-lt {
  background-color: rgba(255, 193, 7, 0.15) !important;
  color: #f59f00 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-purple-lt {
  background-color: rgba(156, 39, 176, 0.15) !important;
  color: #9c27b0 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-gray-lt {
  background-color: rgba(108, 117, 125, 0.15) !important;
  color: #6c757d !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

/* 表格样式优化 */
.table td {
  padding: 0.75rem;
  vertical-align: middle;
}

.table th {
  font-weight: 600;
  background-color: #f8f9fa;
  border-bottom: 2px solid #dee2e6;
}

.badge {
  display: inline-block;
  font-weight: 500;
  line-height: 1.2;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
}

/* 添加描述列的样式 */
td[title] {
  cursor: help;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 添加选中行的样式 */
.selected-row {
  background-color: rgba(32, 107, 196, 0.1) !important;
}

tr {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

tr:hover {
  background-color: rgba(32, 107, 196, 0.05);
}

/* 备注列样式 */
.remark-cell {
  max-width: 600px;
  min-width: 300px;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 高级搜索面板样式 */
.form-label {
  font-weight: 500;
  margin-bottom: 0.5rem;
  color: #374151;
}

.form-select, .form-control {
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-select:focus, .form-control:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 分页按钮样式 */
.btn-group .btn {
  font-size: 0.875rem;
  padding: 0.375rem 0.75rem;
}

.btn-outline-primary {
  color: #3b82f6;
  border-color: #3b82f6;
}

.btn-outline-primary:hover {
  background-color: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

.btn-outline-primary:disabled {
  color: #9ca3af;
  border-color: #9ca3af;
  cursor: not-allowed;
}

.btn-info {
  background-color: #06b6d4;
  border-color: #06b6d4;
  color: white;
}

.btn-info:hover {
  background-color: #0891b2;
  border-color: #0891b2;
}

/* 搜索框样式 */
.form-control-sm {
  height: calc(1.5em + 0.5rem + 2px);
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
  border-radius: 0.2rem;
}

/* 按钮样式优化 */
.btn {
  padding: 0.375rem 0.75rem;
  font-size: 0.875rem;
  line-height: 1.5;
  border-radius: 0.2rem;
  transition: all 0.15s ease-in-out;
}

.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style> 